package com.blog.controller;
import java.util.Date;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import com.blog.entity.User;
import com.blog.service.UserService;
import com.blog.service.Impl.UserServiceImpl;

@WebServlet("/ReGister.do")
public class ReGisterServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		UserService userService = new UserServiceImpl();
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String sex = request.getParameter("sex");
		String email = request.getParameter("email");
		String birthday = request.getParameter("birthday");
		String individualResume = request.getParameter("individualResume");
		String phone = request.getParameter("phone");
		Part part = request.getPart("headImg");
		String headImg = "";
		if(part == null ||part.getSize()>2*1024*1024 || !part.getContentType().contains("image")) {
			request.setAttribute("headMsg", "请选择2M以内的图片文件作为头像");
			request.getRequestDispatcher("register.jsp");
		}else {
			String savePath = "C:/headImgs/";
			String fileName = new Date().getTime()+"_"+part.getSubmittedFileName();
			part.write(savePath+fileName);
			headImg = "C:/WeBlog/userAlbumImgs/"+fileName;
		}
		User user = new User();
		user.setIndividualResume(individualResume);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date userBirth = sdf.parse(birthday);
			user.setUserBirth(userBirth);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		user.setUserEmail(email);
		user.setUserHeadImg(headImg);
		user.setUserName(username);
		user.setUserPass(password);
		user.setUserPhone(phone);
		user.setUserSex(sex);
		int result = userService.insterUser(user);
		if(result == 1){
			response.sendRedirect("login.jsp");
		}else if(result == 0){
			request.getRequestDispatcher("register.jsp").forward(request,response);
		}else if(result == -1){
			request.getRequestDispatcher("register.jsp").forward(request,response);
		}
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
